package com.heisen.file.domin.impl;

import cn.hutool.core.io.FileUtil;
import com.heisen.base.utils.TimeUtils;
import com.heisen.file.domin.FileStorageService;
import com.heisen.file.dto.FileDto;
import com.heisen.file.entity.OpFile;
import com.heisen.file.enums.FileStatusEnum;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author sen
 * @description
 * @date 2024/3/11 9:58
 */
@Slf4j
@Service
@ConditionalOnProperty(value = "file.service.name", havingValue = "qiNiuYun", matchIfMissing = false)
public class QiNiuYunFileStorageService implements FileStorageService  {


    private static final String accessKey = "4HWY0PoaObUJpqbSTacwB9AkjaFezSlaf8G2csOT";
    private static final String secretKey = "WEGG_z1YXQ9Ck4hHZSS-qOedeVCtJNw2ngcKxQWX";

    @SneakyThrows
    @Override
    public List<OpFile> upload(MultipartFile[] files, FileDto fileDto) {

        List<OpFile> fileUrlList = new ArrayList<>();
        Configuration cfg = new Configuration(new Region.Builder()
                .srcUpHost("http://218.201.45.176:8008/upQos/")
                .accUpHost("http://218.201.45.176:8008/upQos/")
                .build());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;
        UploadManager manager = new UploadManager(cfg);


        Auth auth = Auth.create(accessKey, secretKey);


        for (MultipartFile file : files) {

            String originalFilename = file.getOriginalFilename();
            //获取文件拓展名
            String extName = FileUtil.extName(originalFilename);
            log.info("文件拓展名:" + extName);
            //            生成新的文件名，存入到minio
            //  long millSeconds = Instant.now().toEpochMilli();
            String ymdhms = TimeUtils.getCurrentTime_ymdhms();
            String qiNiuYunFileName = ymdhms +"-"+ RandomStringUtils.randomNumeric(12) + "." + extName;

            String fileName = qiNiuYunFileName;
            String folderName = fileDto.getFolderName();
            if(folderName !=null)  qiNiuYunFileName = folderName+ "/"+ qiNiuYunFileName;

            String contentType = file.getContentType();
            log.info("文件mime:{}", contentType);
            //            返回文件大小,单位字节
            long size = file.getSize();
            log.info("文件大小：" + size);

            String bucketName = fileDto.getStoreService();

            String upToken = auth.uploadToken(bucketName);

            Response put = manager.put(file.getBytes(), qiNiuYunFileName, upToken);


            // 文件对象
            OpFile opFile = new OpFile();
            opFile.setOriginalName(originalFilename);
            opFile.setFolderName(StringUtils.isNoneEmpty(folderName)?folderName:bucketName);
            opFile.setCreatetime(TimeUtils.nowDate());
            opFile.setStoreService(bucketName);
            opFile.setStatus(FileStatusEnum.SUCCESS.getStatus());
            opFile.setStorePath(qiNiuYunFileName) ;
            opFile.setFileName(fileName);
            opFile.setSize(size);
            // String fileUrl = fileUrl(bucketName, minioFileName);

            fileUrlList.add(opFile);
        }

        return fileUrlList;
    }

    @SneakyThrows
    @Override
    public String fileUrl(String bucketName, String fileName) {


        // 获取文件路径时需要写这个桶域名，然后做替换，这个桶域名会被用于加密。所以需要后替换
        String domainOfBucket = "http://aike-info-qos.iot-st4.cmiot-solutions.com";
        String encodedFileName = URLEncoder.encode(fileName, "utf-8").replace("+", "%20");
        String publicUrl = String.format("%s/%s", domainOfBucket, encodedFileName);

        Auth auth = Auth.create(accessKey, secretKey);
        //1小时，可以自定义链接过期时间
        long expireInSeconds = 36000;
        String finalUrl = auth.privateDownloadUrl(publicUrl, expireInSeconds);
        System.out.println(finalUrl);
        String fileUrl = finalUrl.replaceFirst("http://aike-info-qos.iot-st4.cmiot-solutions.com",
                "http://218.201.45.176:8008/aikeInfoQos");
        System.out.println(fileUrl);

        return fileUrl;
    }

    @Override
    public void delete(String bucketName, String fileName) {

    }

    @Override
    public void download(String bucketName, String fileName, HttpServletResponse response) {

    }
}
